<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import DeptApi from '@/api/dept'
import { useDeptStore } from '@/store/modules/dept'
import { DeptListType } from '@/api/dept/type'
const DeptStore = useDeptStore()
const ids = ref<number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await DeptApi.GetDeptList({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res
    }
  },
  fetchDelApi: async () => {
    const res = await DeptApi.DeletDept(unref(ids)[0])
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: '序号',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'parentId',
    label: '上级部门',
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        checkStrictly: true,
        checkOnClickNode: true,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      },
      optionApi: async () => {
        const res = await DeptApi.GetDeptListTree()
        const i = [{ children: res.data, disabled: false, id: 0, label: '根节点' }]
        return i
      }
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'deptName',
    label: '部门名称',
    search: {
      component: 'Input',
      componentProps: {
        placeholder: '部门名称'
      }
    }
  },
  {
    field: 'status',
    label: '状态',
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '状态',
        options: [
          {
            value: '0',
            label: '正常'
          },
          {
            value: '1',
            label: '停用'
          }
        ]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const status = data.row.status
          return (
            <>
              <ElTag type={status == '0' ? 'success' : 'danger'}>
                {status == '0' ? '正常' : '停用'}
              </ElTag>
            </>
          )
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: '0',
            label: '正常'
          },
          {
            value: '1',
            label: '停用'
          }
        ]
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElTag type={data.status == '0' ? 'success' : 'danger'}>
                {data.status == '0' ? '正常' : '停用'}
              </ElTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'leader',
    label: '负责人',
    search: {
      hidden: true
    },
    form: {
      // hidden: true
    }
  },
  {
    field: 'phone',
    label: '联系电话',
    search: {
      hidden: true
    },
    form: {
      // hidden: true
    }
  },
  {
    field: 'email',
    label: '邮箱',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
    // form: {
    //   hidden: true
    // }
  },
  {
    field: 'orderNum',
    label: '显示顺序',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'InputNumber'
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: '备注',
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 3
      },
      colProps: {
        span: 24
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{data.remark}</>
        }
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: '操作',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'detail')}>
                {t('查看')}
              </span>
              <span class="TableBtn" onClick={() => action({ parentId: data.row.deptId }, 'add')}>
                {t('添加')}
              </span>
              <span class="TableBtn" onClick={() => action(data.row, 'edit')}>
                {t('修改')}
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DeptListType | null>(null)
const actionType = ref('')

const delLoading = ref(false)

const delData = async (row: DeptListType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.deptId]
    : elTableExpose?.getSelectionRows().map((v: DeptListType) => v.deptId) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: DeptListType, type: string) => {
  dialogTitle.value = t(type === 'edit' ? '修改' : '添加')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res: any = ref(false)
    if (actionType.value == 'add') {
      res.value = await DeptApi.AddDept(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      res.value = await DeptApi.EditDept(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
      DeptStore.setFacilityTypeDetail() //其他页面获取部门信息
    }
  }
}
</script>

<template>
  <ContentWrap>
    <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
      <Icon icon="ep:plus" :size="12" />添加
    </BaseButton>
    <Search :schema="allSchemas.tableColumns" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="deptId"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType == 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style scoped>
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
</style>
